﻿namespace Shortcuts.Common
{
    using Microsoft.Phone.Shell;
    using Shortcuts.Globalization;
    using System;
    using System.Linq;

    public class Tile
    {
        public Settings Settings { get; private set; }

        public Tile(Settings settings)
        {
            this.Settings = settings;
        }

        Uri uri;
        public Uri NavigationUri
        {
            get
            {
                if (uri == null)
                {
                    uri = new Uri(string.Format("/Views/NavigationPage.xaml?settings={0:G}", Settings), UriKind.Relative);
                }
                return uri;
            }
        }

        public void Pin()
        {
            if (Settings == Common.Settings.All)
            {
                throw new NotSupportedException(string.Format("Unsupport the Settings.{0}", Settings));
            }

            StandardTileData tile = new StandardTileData
            {
                Title = Settings.Named().Localized(),
                BackgroundImage = new Uri(string.Format("/Images/{0:G}.png", Settings), UriKind.Relative)
            };

            var oldTile = ShellTile.ActiveTiles.FirstOrDefault(x => x.NavigationUri.OriginalString == NavigationUri.OriginalString);
            if (oldTile != null)
            {
                oldTile.Update(tile);
            }
            else
            {
                ShellTile.Create(uri, tile);
            }
        }

        public void Delete()
        {
            if (Settings == Common.Settings.All)
            {
                throw new NotSupportedException(string.Format("Unsupport the Settings.{0}", Settings));
            }

            var oldTile = ShellTile.ActiveTiles.FirstOrDefault(x => x.NavigationUri.OriginalString == NavigationUri.OriginalString);
            if (oldTile != null)
            {
                oldTile.Delete();
            }
        }
    }
}
